const config = require("../config/index.js");
//添加事件结束
Promise.prototype.finally = function (callback) {
  var Promise = this.constructor;
  return this.then(
    function (value) {
      Promise.resolve(callback()).then(
        function () {
          return value;
        }
      );
    },
    function (reason) {
      Promise.resolve(callback()).then(
        function () {
          throw reason;
        }
      );
    }
  );
}
const $wx = (options) => {
  let city = wx.getStorageSync("DT-CITY") || "深圳";
  let token = wx.getStorageSync("DT-TOKEN") || "";
  return new Promise((resolve,reject) => {
    if(!options.loading){
      wx.showLoading({
        title: '加载中...',
      })
    }
    wx.request({
      url: `${config.API_URL}${options.url}`,
      data: { ...options.data, city: city, token:token} || {},
      method:options.method || "GET",
      header:options.header?options.header:{
        "content-type": "application/json;charset=utf-8"
      },
      success:function(res){
        //simple handle request fail
        let result = res.data;
        if (result.resCode == 0){
          resolve(result)
        }else{
          if(result.resCode == 401){
            wx.redirectTo({
              url: '/pages/login/index',
            });
            return false;
          }
          wx.showToast({
            duration:1000,
            title: result.resMsg || '加载失败。。。',
            icon:"error"
          });
          reject(res.data);
        }
      },
      fail:function(err){
        reject(err);
      },
      complete:function(){
        wx.hideLoading();
      }
    })
  }).catch((err)=>{
    console.log(err);
  })
}
module.exports = $wx;